from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from django.db.models import Q
from user.dataCheck import DataCheck
from user.models import IPSystem, User, VSession
from storehouse.models import Storehouse, StorehouseConnect
from log.models import UserLog, StoreHouseLog, SoftwareLog
from software.utils import fileStore
import pdb, os, xlwt, datetime, time, json, random, requests

import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")

datacheck = DataCheck()


def getIPList(request, *args, **kwargs):
    """
        url    : /log/ipadmin/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'IPlist':[{
                    'userType':null,//用户类型
                    'userIP':null,//IP地址
                    'ipState':null,//IP状态               
                    'username':null,//用户名
                    'duration':null,//登录时长
                    'company':null,//所属单位
                    'warZone':null,//所属战区
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    IPlist = IPSystem.objects.all()
    if IPlist.exists():
        totalNum = len(IPlist)
        IPlists = []
        result = IPlist[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                 requestParam['page'] *
                                                                                                 requestParam[
                                                                                                     'maxItem'])]

        for userIP in result:
            # IPState = IPSystem.objects.filter(userIP=userIP.userIP,user=userIP.user)
            durationItem = userIP.duration
            if durationItem == '':
                durationItem = 0
            else:
                pass
            IPlist = {
                'userIP': userIP.userIP,
                'userType': userIP.user.userType,
                'id': userIP.id,
                'userId': userIP.user.id,
                'username': userIP.user.username,
                'ipState': userIP.IPState,
                'duration': durationItem,
                'company': userIP.user.company.name,
                'warZone': userIP.user.warZone.name,

            }
            IPlists.append(IPlist)
    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "IPlist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "IPlist": IPlists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def IPLogScreen(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            warZoneId:data.warZoneId,//战区id
            companyId:data.companyId,//单位id
            usertype:data.usertype,//用户类型
            username:data.username,//关键词


            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'IPdata':[{
                    'userType':null,//用户类型
                    'userIP':null,//IP地址
                    'ipState':null,//IP状态               
                    'username':null,//用户名
                    'duration':null,//登录时长
                    'company':null,//所属单位
                    'warZone':null,//所属战区
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 从数据库获取软件时的filter条件字典
    filterDict = {}

    if requestParam['username'] != '':
        filterDict['user__username__contains'] = requestParam['username']

    if requestParam['usertype'] != '':
        filterDict['user__userType'] = requestParam['usertype']

    if requestParam['warZoneId'] != None:
        filterDict['user__warZone__id'] = requestParam['warZoneId']
        if requestParam['companyId'] != None:
            filterDict['user__company__id'] = requestParam['companyId']
            # pdb.set_trace()
    IPlist = IPSystem.objects.filter(**filterDict)

    if IPlist.exists():
        totalNum = len(IPlist)
        IPlists = []
        result = IPlist[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                 requestParam['page'] *
                                                                                                 requestParam[
                                                                                                     'maxItem'])]

        for userIP in result:
            # IPState = IPSystem.objects.filter(userIP=userIP.userIP,user=userIP.user)
            durationItem = userIP.duration
            if durationItem == '':
                durationItem = 0
            else:
                pass

            IPlist = {
                'userIP': userIP.userIP,
                'userType': userIP.user.userType,
                'id': userIP.id,
                'username': userIP.user.username,
                'userId': userIP.user.id,
                'ipState': userIP.IPState,
                'company': userIP.user.company.name,
                'warZone': userIP.user.warZone.name,
                'duration': durationItem,
            }
            IPlists.append(IPlist)
    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "IPlist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "IPlist": IPlists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def getLog(request, *args, **kwargs):
    """
        url    : /log/list/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem
               type:data.type,//日志类型，0：运行日志，1：用户日志，3：软件日志

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'list':[{
                    'id':null,//仓库id，用户id
                    'name':null,//仓库名称，用户名称，
                    'softwareName':null,//若为软件记录为软件名，其余无
                    'operate':null,//操作
                    'createtime':null,//创建时间
                    'userIP':null,//若为用户日志为用户IP地址，其余无
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam['token'])
    usertype = user.userType
    # pdb.set_trace()    
    if usertype == '2':
        if requestParam['logType'] == '0':
            masterStorehouseList = Storehouse.objects.filter(user=user)
            masterStorehouse = masterStorehouseList[0]
            if masterStorehouse.isMasterStore == True:
                storeConnectList = StorehouseConnect.objects.filter(masterStorehouseId=masterStorehouse.id,
                                                                    connectState='2')
                if storeConnectList.exists():
                    storeConnectLists = []

                    storehouseLists = []

                    for storeConnect in storeConnectList:
                        storehouseList = Storehouse.objects.filter(pk=storeConnect.subStorehouseId)

                        for storehouse in storehouseList:
                            storehouseList = {
                                'id': storehouse.id,
                                'name': storehouse.storehouseName,
                                'warZoneName': storehouse.warZone.name,
                                'companyName': storehouse.company.name,
                                'runstate': storehouse.runState,
                                'createtime': storehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                            }
                            storehouseLists.append(storehouseList)

                    storehouseList = {
                        'id': masterStorehouse.id,
                        'name': masterStorehouse.storehouseName,
                        'warZoneName': masterStorehouse.warZone.name,
                        'companyName': masterStorehouse.company.name,
                        'runstate': masterStorehouse.runState,
                        'createtime': masterStorehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    storehouseLists.append(storehouseList)

                    totalNum = len(storehouseLists)
                    result = storehouseLists[
                             min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

                else:
                    storehouseLists = []

                    for storehouse in masterStorehouseList:
                        storehouseList = {
                            'id': storehouse.id,
                            'name': storehouse.storehouseName,
                            'warZoneName': storehouse.warZone.name,
                            'companyName': storehouse.company.name,
                            'runstate': storehouse.runState,
                            'createtime': storehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                        }
                        storehouseLists.append(storehouseList)

                    totalNum = len(storehouseLists)
                    result = storehouseLists[
                             min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]
                data = {
                    'code': 0,
                    'msg': 'success',
                    "totalNum": totalNum,
                    "logList": result,
                }
                logger_request.info(data)
                return JsonResponse(data)

            elif masterStorehouse.isMasterStore != True:
                storehouseLists = []
                storehouseList = {
                    'id': masterStorehouse.id,
                    'name': masterStorehouse.storehouseName,
                    'warZoneName': masterStorehouse.warZone.name,
                    'companyName': masterStorehouse.company.name,
                    'runstate': masterStorehouse.runState,
                    'createtime': masterStorehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                storehouseLists.append(storehouseList)
                data = {
                    'code': 0,
                    'msg': 'success',
                    "totalNum": 1,
                    "logList": storehouseLists,
                }
                logger_request.info(data)
                return JsonResponse(data)


            else:
                data = {
                    'code': 0,
                    'msg': 'not exist',
                    "totalNum": 0,
                    "logList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)


        elif requestParam['logType'] == '1':
            userList = User.objects.all()
            if userList.exists():
                totalNum = len(userList)
                userLists = []
                result = userList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                           requestParam[
                                                                                                               'page'] *
                                                                                                           requestParam[
                                                                                                               'maxItem'])]

                for user in result:
                    userList = {
                        'id': user.id,
                        'name': user.username,
                        'userType': user.userType,
                        'createtime': user.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'warZoneName': user.warZone.name,
                        'companyName': user.company.name,
                    }
                    userLists.append(userList)
            else:
                data = {
                    'code': 0,
                    'msg': 'not exist',
                    "totalNum": 0,
                    "logList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)

            data = {
                'code': 0,
                'msg': 'success',
                "totalNum": totalNum,
                "logList": userLists,
            }
            logger_request.info(data)
            return JsonResponse(data)

            # elif requestParam['logType'] == '3':
        #     softwareLogList = SoftwareLog.objects.all()
        #     if softwareLogList.exists(): 
        #         totalNum = len(softwareLogList)
        #         softwareLogLists = []
        #         result = softwareLogList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
        #                                                                                                 requestParam['page'] *
        #                                                                                                 requestParam['maxItem'])]

        #         for softwarelog in result:
        #             softwareLogList = {
        #                 'id': softwarelog.id,
        #                 'operate': softwarelog.operate,                
        #                 'createtime':softwarelog.createTime.strftime('%Y-%m-%d %H:%M:%S'),
        #                 'softwareName': softwarelog.softwareName,
        #             }
        #             softwareLogLists.append(softwareLogList)
        #     else:

        #         data = {
        #             'code': 0,
        #             'msg': 'not exist',
        #             "totalNum": 0,
        #             "logList": [],
        #         }
        #         logger_request.info(data)
        #         return JsonResponse(data)        

        #     data = {
        #         'code': 0,
        #         'msg': 'success',
        #         "totalNum": totalNum,
        #         "logList": softwareLogLists,
        #     }
        #     logger_request.info(data)
        #     return JsonResponse(data)         

        else:

            data = {
                'code': 0,
                'msg': 'error',
                "totalNum": 0,
                "logList": [],
            }
            logger_request.info(data)
            return JsonResponse(data)

    else:

        data = {
            'code': 0,
            'msg': 'usertype error',
            "totalNum": 0,
            "logList": [],
        }
        logger_request.info(data)
        return JsonResponse(data)


def logScreen(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            startDate:data.start,//起始时间
            endDate:data.enddata,//结束时间
            name:data.name,//关键词
            type:data.type,//日志类型，0：运行日志，1：用户日志，3：软件日志            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'loglist':[{
                'id':null,//仓库id，用户id
                'name':null,//仓库名称，用户名称，
                'softwareName':null,//若为软件记录为软件名，其余无
                'operate':null,//操作
                'createtime':null,//创建时间
                'userIP':null,//若为用户日志为用户IP地址，其余无
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 从数据库获取软件时的filter条件字典
    filterDict = {}
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if requestParam['startDate'] != '' and requestParam['endDate'] != '':
        filterDict['createTime__gte'] = requestParam['startDate']
        filterDict['createTime__lte'] = requestParam['endDate']

    if requestParam['logType'] == '0':
        if requestParam['name'] != '':
            filterDict['storehouseName__contains'] = requestParam['name']
    elif requestParam['logType'] == '1':
        if requestParam['name'] != '':
            filterDict['username__contains'] = requestParam['name']
    elif requestParam['logType'] == '3':
        if requestParam['name'] != '':
            filterDict['software__softwareName__contains'] = requestParam['name']
    else:
        data = {
            "code": 0,
            "msg": "type Error",
            'totalNum': 0,
            'logList': []
        }
        logger_request.info(data)
        return JsonResponse(data)
        # pdb.set_trace()
    storehouse = Storehouse.objects.filter(user=user).first()

    if userType == '2':
        if requestParam['logType'] == '0':
            masterStorehouseList = Storehouse.objects.filter(user=user)
            masterStorehouse = masterStorehouseList[0]
            if masterStorehouse.isMasterStore == True:
                storeConnectList = StorehouseConnect.objects.filter(masterStorehouseId=masterStorehouse.id).filter(
                    ~Q(connectState='3'))
                if storeConnectList.exists():
                    storeConnectLists = []

                    storehouseLists = []

                    for storeConnect in storeConnectList:
                        storehouseList = Storehouse.objects.filter(pk=storeConnect.subStorehouseId, **filterDict)

                        for storehouse in storehouseList:
                            storehouseList = {
                                'id': storehouse.id,
                                'name': storehouse.storehouseName,
                                'warZoneName': storehouse.warZone.name,
                                'companyName': storehouse.company.name,
                                'runstate': storehouse.runState,
                                'createtime': storehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                            }
                            storehouseLists.append(storehouseList)
                    storehouseItem = Storehouse.objects.filter(user=user, **filterDict)
                    if storehouseItem.exists():
                        masterStorehouseItem = storehouseItem[0]
                        storehouseList = {
                            'id': masterStorehouseItem.id,
                            'name': masterStorehouseItem.storehouseName,
                            'warZoneName': masterStorehouseItem.warZone.name,
                            'companyName': masterStorehouseItem.company.name,
                            'runstate': masterStorehouseItem.runState,
                            'createtime': masterStorehouseItem.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                        }
                        storehouseLists.append(storehouseList)

                    totalNum = len(storehouseLists)
                    result = storehouseLists[
                             min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

                else:
                    storehouseLists = []
                    storehouseItem = Storehouse.objects.filter(user=user, **filterDict)
                    if storehouseItem.exists():

                        for storehouse in storehouseItem:
                            storehouseList = {
                                'id': storehouse.id,
                                'name': storehouse.storehouseName,
                                'warZoneName': storehouse.warZone.name,
                                'companyName': storehouse.company.name,
                                'runstate': storehouse.runState,
                                'createtime': storehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                            }
                            storehouseLists.append(storehouseList)

                        totalNum = len(storehouseLists)
                        result = storehouseLists[
                                 min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                          requestParam[
                                                                                                              'page'] *
                                                                                                          requestParam[
                                                                                                              'maxItem'])]
                    else:
                        data = {
                            'code': 0,
                            'msg': 'success',
                            "totalNum": 0,
                            "logList": [],
                        }
                        logger_request.info(data)
                        return JsonResponse(data)
                data = {
                    'code': 0,
                    'msg': 'success',
                    "totalNum": totalNum,
                    "logList": result,
                }
                logger_request.info(data)
                return JsonResponse(data)

            elif masterStorehouse.isMasterStore != True:
                storehouseLists = []
                storehouseItem = Storehouse.objects.filter(user=user, **filterDict)
                if storehouseItem.exists():
                    masterStorehouseItem = storehouseItem[0]
                    storehouseList = {
                        'id': masterStorehouseItem.id,
                        'name': masterStorehouseItem.storehouseName,
                        'warZoneName': masterStorehouseItem.warZone.name,
                        'companyName': masterStorehouseItem.company.name,
                        'runstate': masterStorehouseItem.runState,
                        'createtime': masterStorehouseItem.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    storehouseLists.append(storehouseList)
                else:
                    data = {
                        'code': 0,
                        'msg': 'success',
                        "totalNum": 0,
                        "logList": [],
                    }
                    logger_request.info(data)
                    return JsonResponse(data)

                data = {
                    'code': 0,
                    'msg': 'success',
                    "totalNum": 1,
                    "logList": storehouseLists,
                }
                logger_request.info(data)
                return JsonResponse(data)


            else:
                data = {
                    'code': 0,
                    'msg': 'not exist',
                    "totalNum": 0,
                    "logList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)

        elif requestParam['logType'] == '1':
            userList = User.objects.filter(**filterDict)
            if userList.exists():
                totalNum = len(userList)
                userLists = []
                result = userList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                           requestParam[
                                                                                                               'page'] *
                                                                                                           requestParam[
                                                                                                               'maxItem'])]

                for user in result:
                    userList = {
                        'id': user.id,
                        'name': user.username,
                        'userType': user.userType,
                        'createtime': user.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'warZoneName': user.warZone.name,
                        'companyName': user.company.name,
                    }
                    userLists.append(userList)
            else:
                data = {
                    'code': 0,
                    'msg': 'not exist',
                    "totalNum": 0,
                    "logList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)

            data = {
                'code': 0,
                'msg': 'success',
                "totalNum": totalNum,
                "logList": userLists,
            }
            logger_request.info(data)
            return JsonResponse(data)



        # elif requestParam['logType'] == '3':
        #     softwareLogList = SoftwareLog.objects.filter(**filterDict)
        #     if softwareLogList.exists():
        #         totalNum = len(softwareLogList)
        #         softwareLogLists = []
        #         result = softwareLogList[
        #                  min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
        #                                                                                           requestParam['page'] *
        #                                                                                           requestParam[
        #                                                                                               'maxItem'])]

        #         for softwarelog in result:
        #             softwareLogList = {
        #                 'id': softwarelog.id,
        #                 'operate': softwarelog.operate,
        #                 'createtime': softwarelog.createTime.strftime('%Y-%m-%d %H:%M:%S'),
        #                 'softwareName': softwarelog.softwareName,
        #             }
        #             softwareLogLists.append(softwareLogList)
        #     else:

        #         data = {
        #             'code': 0,
        #             'msg': 'not exist',
        #             "totalNum": 0,
        #             "logList": [],
        #         }
        #         logger_request.info(data)
        #         return JsonResponse(data)

        # data = {
        #     'code': 0,
        #     'msg': 'success',
        #     "totalNum": totalNum,
        #     "logList": softwareLogLists,
        # }
        # logger_request.info(data)
        # return JsonResponse(data)

        else:

            data = {
                'code': 0,
                'msg': 'error',
                "totalNum": 0,
                "logList": [],
            }
            logger_request.info(data)
            return JsonResponse(data)

    else:
        data = {
            'code': 0,
            'msg': 'usertype error',
            "totalNum": 0,
            "list": [],
        }
        logger_request.info(data)
        return JsonResponse(data)


def logCheck(request, *args, **kwargs):
    """
        url    : /log/check/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
                id:data.storenid,//仓库id或用户id
                type:data.type,//0:运行日志；1:用户日志
            
        },
        resData:{
            'storename':null,//仓库名称
            'storestate':null,//仓库状态 
            'action':[{
                'time':null,
                'name':null,//仓库名称或软件名称
                'option':null,//系统重启、系统离线、系统更换节点等str，下线软件、审核软件、删除软件等str
            }],
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    if requestParam['token'] != '':
        ##首次请求
        user = datacheck.getUser(requestParam['token'])
        usertype = user.userType
        # storehouse = Storehouse.objects.filter(user=user).first()
        # pdb.set_trace()    
        if usertype == '2':
            if requestParam['logType'] == '0':
                storehouseConnect = StorehouseConnect.objects.filter(subStorehouseId=requestParam['id'])
                if storehouseConnect.exists():
                    storehouse = Storehouse.objects.get(pk=requestParam['id'])
                    filterDict = {}
                    filterDict['storeIP'] = storehouse.storeIP
                    filterDict['storePort'] = storehouse.storePort
                    filterDict['storehouseName'] = storehouse.storehouseName
                    filterDict['logType'] = requestParam['logType']
                    filterDict['page'] = requestParam['page']
                    filterDict['maxItem'] = requestParam['maxItem']
                    data1 = requests.post(
                        "http://" + storehouse.storeIP + ":" + storehouse.storePort + "/api/log/" + 'check/',
                        data=filterDict)
                    data = json.loads(data1.text)
                    return JsonResponse(data)
                else:
                    storehouse = Storehouse.objects.get(pk=requestParam['id'])
                    storehouseLoglist = StoreHouseLog.objects.filter(storeHouse=storehouse)
                    if storehouseLoglist.exists():
                        totalNum = len(storehouseLoglist)
                        storehouseLoglists = []
                        result = storehouseLoglist[
                                 min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                          requestParam[
                                                                                                              'page'] *
                                                                                                          requestParam[
                                                                                                              'maxItem'])]

                        for storehouselog in result:
                            storehouseLoglist = {
                                'id': storehouselog.storeHouse.id,
                                'name': storehouselog.storeHouse.storehouseName,
                                'storestate': storehouselog.storeHouse.runState,
                                'option': storehouselog.operate,
                                'time': storehouselog.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                            }
                            storehouseLoglists.append(storehouseLoglist)

                    else:
                        data = {
                            'code': 0,
                            'msg': 'not exist',
                            "totalNum": 0,
                            "action": [],
                        }
                        logger_request.info(data)
                        return JsonResponse(data)
                    data = {
                        'code': 0,
                        'msg': 'success',
                        "totalNum": totalNum,
                        "action": storehouseLoglists,
                    }
                    logger_request.info(data)
                    return JsonResponse(data)

            elif requestParam['logType'] == '1':
                user1 = User.objects.get(pk=requestParam['id'])
                userLogList = UserLog.objects.filter(user=user1)
                if userLogList.exists():
                    totalNum = len(userLogList)
                    userLogLists = []
                    result = userLogList[
                             min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

                    for userlog in result:
                        userLogList = {
                            'id': userlog.user.id,
                            'name': userlog.user.username,
                            'option': userlog.operate,
                            'time': userlog.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                            'userIP': userlog.userIP,
                        }
                        userLogLists.append(userLogList)
                else:
                    data = {
                        'code': 0,
                        'msg': 'not exist',
                        "totalNum": 0,
                        "action": [],
                    }
                    logger_request.info(data)
                    return JsonResponse(data)

                data = {
                    'code': 0,
                    'msg': 'success',
                    "totalNum": totalNum,
                    "action": userLogLists,
                }
                logger_request.info(data)
                return JsonResponse(data)

            else:
                data = {
                    'code': 0,
                    'msg': 'type error',
                    "totalNum": 0,
                    "action": [],
                }
                logger_request.info(data)
                return JsonResponse(data)

        else:

            data = {
                'code': 0,
                'msg': 'usertype error',
                "totalNum": 0,
                "action": [],
            }
            logger_request.info(data)
            return JsonResponse(data)
    elif requestParam['token'] == '':
        storehouse = Storehouse.objects.get(storehouseName=requestParam['storehouseName'],
                                            storeIP=requestParam['storeIP'], storePort=requestParam['storePort'])
        storehouseLoglist = StoreHouseLog.objects.filter(storeHouse=storehouse)
        if storehouseLoglist.exists():
            totalNum = len(storehouseLoglist)
            storehouseLoglists = []
            result = storehouseLoglist[
                     min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                              requestParam['page'] *
                                                                                              requestParam[
                                                                                                  'maxItem'])]

            for storehouselog in result:
                storehouseLoglist = {
                    'id': storehouselog.storeHouse.id,
                    'name': storehouselog.storeHouse.storehouseName,
                    'storestate': storehouselog.storeHouse.runState,
                    'option': storehouselog.operate,
                    'time': storehouselog.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                storehouseLoglists.append(storehouseLoglist)

        else:
            data = {
                'code': 0,
                'msg': 'not exist',
                "totalNum": 0,
                "action": [],
            }
            logger_request.info(data)
            return JsonResponse(data)
        data = {
            'code': 0,
            'msg': 'success',
            "totalNum": totalNum,
            "action": storehouseLoglists,
        }
        logger_request.info(data)
        return JsonResponse(data)

    # def exportLog(request, *args, **kwargs):
#     """
#         url    : /log/export/
#         method : POST

#     :param request:
#                token: data.token, // 用户的秘钥
#                 idlist:data.storenid,//仓库id或用户id

#         },
#         resData:{
#             'code':null,//
#             'msg':null,// 
#             'wordurl':null
#     """

#     form = request.checkForm
#     requestParam = form.cleaned_data
#     logger_request.info(requestParam)

#     user = datacheck.getUser(requestParam['token'])
#     usertype = user.userType
#     # pdb.set_trace()    
#     if usertype == '2':
#         if requestParam['logType'] == '0':
#             for storehouse in json.loads(requestParam['idlist']):
#                 storehouses = Storehouse.objects.get(pk=storehouse)
#                 storehouseLoglist = StoreHouseLog.objects.filter(storeHouse=storehouses)
#                 if storehouseLoglist.exists():
#                     logBook = xlwt.Workbook(encoding='utf-8')
#                     detailExcel = logBook.add_sheet('日志详情', cell_overwrite_ok=True)
#                     detailExcel.write(0, 1, '导出用户：' + user.username)
#                     detailExcel.write(0, 2, '导出时间：' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
#                     detailExcel.write(1, 0, '仓库')
#                     detailExcel.write(1, 1, '操作')
#                     detailExcel.write(1, 2, '日期')
#                     Row = 2
#                     for storeLog in storehouseLoglist:
#                         storehouseName = storeLog.storeHouse.storehouseName
#                         operate = storeLog.operate
#                         createTime = storeLog.createTime.strftime('%Y-%m-%d %H:%M:%S')
#                         # 写入每一行对应的数据
#                         detailExcel.write(Row, 0, storehouseName)
#                         detailExcel.write(Row, 1, operate)
#                         detailExcel.write(Row, 2, createTime)
#                         Row += 1
#             alphabet = 'abcdefghijklmnopqrstuvwxyz'
#             char = random.choice(alphabet)            
#             logBook.save(os.path.join(tmpDir, + char + "detailExcel.xls"))

#     data = {
#         'msg': 'success',
#         'code': 0,
#         'imageUrl': download(name, str(0), os.path.join(tmpDir, name))[1],
#     }
#     return JsonResponse(data)
